package com.ruoyi.project.common;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.QiniuUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.zerocarbon.domain.Declaration;
import com.ruoyi.project.zerocarbon.domain.DeclareFile;
import com.ruoyi.project.zerocarbon.domain.vo.DeclarationVo;
import com.ruoyi.project.zerocarbon.mapper.DeclarationMapper;
import com.ruoyi.project.zerocarbon.mapper.DeclareFileMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.file.QiniuUtils.getQiniuPath;

/**
 * @类名: UploadController
 * @描述:
 * @作者: liudf
 * @日期: 2021/8/7 21:35
 */
@Api(tags = "七牛文件上传")
@RestController
public class UploadController {
    public static final Logger log = LoggerFactory.getLogger(UploadController.class);
    @Autowired
    private ServerConfig serverConfig;
    @Resource
    private QiniuUtils qiniuUtils;
    @Autowired
    private DeclarationMapper declarationMapper;
    @Autowired
    private DeclareFileMapper declareFileMapper;

    @ApiOperation(value = "七牛上传文件接口")
    @PostMapping(value = "/file/qiniuUpload")
    public AjaxResult fileUpload(MultipartFile file) {
        try
        {
            // 上传文件路径
            // 上传并返回新文件名称
            String url = "declaration/" + System.currentTimeMillis()+"-"+file.getOriginalFilename();
            AjaxResult ajax = AjaxResult.success();
            String qiniuUrl = qiniuUtils.uploadMultipartFile(file, url);
            ajax.put("fileName", file.getOriginalFilename());
            ajax.put("url", qiniuUrl);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "七牛获得token")
    @GetMapping(value = "/file/qiniuToken")
    public AjaxResult qiniuToken() {
        try
        {
            // 上传文件路径
            // 上传并返回新文件名称
            String token = qiniuUtils.getUpToken();
            return AjaxResult.success(token);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("打包七牛zip，根据qiniuzipid是否为空判断是否已经打包")
    @ResponseBody
    @GetMapping("/file/qiniuZip")
    public AjaxResult doQiniuZip(Long declarationId,String isAll) {
        if (StringUtils.isNotEmpty(isAll) && isAll.equals("1")){
            DeclarationVo declarationVo = new DeclarationVo();
            declarationVo.setSaveType(1);
            List<Declaration> declarationList = declarationMapper.selectDeclarationList(declarationVo);
            for (Declaration model:declarationList){
                if (!StringUtils.isEmpty(model.getQiniuzipid())){
                    continue;
                }
                log.info("打包zip 项目id: {}",model.getId());
                try {
                    List<DeclareFile> declareFiles = declareFileMapper.selectByDeclarationId(model.getId());
                    if (!CollectionUtils.isEmpty(declareFiles)){
                        //                打包zip
                        String zipPath = "declaration/zip/"+model.getHead().trim() + "-" + model.getId() + ".zip";
                        List<String> collect = declareFiles.stream().map(DeclareFile::getQiniuPath).collect(Collectors.toList());
                        if (CollectionUtils.isEmpty(collect)){
                            log.info("打包zip QiniuPath: {},getQiniuPath is null",model.getQiniuzippath());
                            continue;
                        }
                        String zipid = qiniuUtils.zipFiles(collect,zipPath);
                        model.setQiniuzipid(zipid);
                        model.setQiniuzippath(getQiniuPath(zipPath));
                        log.info("打包zip QiniuPath: {},zipid:{}",model.getQiniuzippath(),zipid);
                        declarationMapper.updateDeclaration(model);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
            return AjaxResult.success();
        }
        Declaration declaration = declarationMapper.selectDeclarationById(declarationId);
        if (StringUtils.isEmpty(declaration.getQiniuzipid())){
            List<DeclareFile> declareFiles = declareFileMapper.selectByDeclarationId(declarationId);
            if (!CollectionUtils.isEmpty(declareFiles)){
//                打包zip
                String zipPath = "declaration/zip/"+declaration.getHead().trim() + "-" + declarationId + ".zip";
                List<String> collect = declareFiles.stream().map(DeclareFile::getQiniuPath).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect)){
                    log.info("打包zip QiniuPath: {},getQiniuPath is null",declaration.getQiniuzippath());
                    return AjaxResult.success();
                }
                String zipid = qiniuUtils.zipFiles(collect,zipPath);
                declaration.setQiniuzipid(zipid);
                declaration.setQiniuzippath(getQiniuPath(zipPath));
                log.info("打包zip QiniuPath: {},zipid:{}",declaration.getQiniuzippath(),zipid);
                declarationMapper.updateDeclaration(declaration);
                return AjaxResult.success(declaration.getQiniuzippath());
            }
        }
        return AjaxResult.success();
    }

    @GetMapping(value = "/file/qiniuUpload/history")
    public AjaxResult fileUpload(String filePath,String dirPath,Long id,String isAll) {
        try
        {
            // 上传文件路径
            // 上传并返回新文件名称
            if (id != null){
                DeclareFile declareFile = declareFileMapper.selectDeclareFileById(id);
                filePath = declareFile.getPath();
                String url = "declaration/" + new File(filePath).getName();
                log.info("filePath:{},url:{}",filePath,url);
                String qiniuUrl = qiniuUtils.upload(filePath, url);
                declareFile.setQiniuPath(qiniuUrl);
                declareFile.setUpdateTime(new Date());
                declareFileMapper.updateDeclareFile(declareFile);
                return AjaxResult.success(qiniuUrl);
            }
            if (StringUtils.isNotEmpty(isAll) && isAll.equals("1")){
                List<DeclareFile> declareFiles = declareFileMapper.selectDeclareFileList(new DeclareFile());
                for (DeclareFile declareFile:declareFiles){
                    if (StringUtils.isEmpty(declareFile.getPath()) || StringUtils.isNotEmpty(declareFile.getQiniuPath())){
                        continue;
                    }
                    filePath = declareFile.getPath();
                    String url = "declaration/" + new File(filePath).getName();
                    log.info("isAll 1,filePath:{},url:{}",filePath,url);
                    String qiniuUrl = qiniuUtils.upload(filePath, url);
                    declareFile.setQiniuPath(qiniuUrl);
                    declareFile.setUpdateTime(new Date());
                    declareFileMapper.updateDeclareFile(declareFile);
                }
                return AjaxResult.success();
            }
            if (StringUtils.isNotEmpty(filePath)){
                String url = "declaration/" + new File(filePath).getName();
                String qiniuUrl = qiniuUtils.upload(filePath, url);
                return AjaxResult.success(qiniuUrl);
            }
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 调用七牛云压缩完成后,回调接口
     * @param status
     * @return
     */
    @RequestMapping(value = "/file/getQiniuResult", method = RequestMethod.POST)
    public void getQiniuResult(@RequestBody QiniuStatus status) {
        int code = status.getCode();//状态码 0：成功，1：等待处理，2：正在处理，3：处理失败，4：成功但通知失败。
        String desc = status.getDesc();//与状态码相对应的详细描述。
        if (code==0) {
            String persistentId = status.getId();//持久化处理的进程 ID，即前文中的<persistentId>
            Declaration declaration = declarationMapper.selectDeclarationByQiniuId(persistentId);
            if (declaration == null){
                return;
            }
            List<QiniuResult> items = status.getItems();
            if(items!=null && items.size()!=0){
                QiniuResult result =items.get(0);
                String resultCmd =result.getCmd();
                int resultCode =result.getCode();
                String resultDesc =result.getDesc();
                log.info("################persistentId=="+persistentId+"resultCmd=="+resultCmd+" resultCode=="+resultCode+" resultDesc=="+resultDesc);
                if(resultCode==0){
                    String key =result.getKey();
                    declaration.setQiniuzippath(getQiniuPath(key));
                    log.info("压缩包名称是="+key+"qiniuzipPath="+declaration.getQiniuzippath());
                    declarationMapper.updateDeclaration(declaration);
                }

            }

        }else if(code==3){
            log.info("处理失败,原因是:"+desc);
        }else if(code ==1 || code==2){
            log.info("正在处理中...");
        }else if(code==4){
            log.info("处理成功但通知失败");
        }
    }

}

